# -*- coding:utf-8 -*-
import os
import re

import thread
from time import sleep

from utils.adb_core import AdbCore


class AdbDevices:
    def __init__(self, adb):
        self.adb = adb
        self.sn_selected = ""
        self.devices_sn = []
        self.devices = {}

    def update_sn(self, new_sn):
        self.adb.set_sn(new_sn)

    def update_sn_by_index(self, index_selected):
        self.sn_selected = self.devices_sn[index_selected]
        self.adb.set_sn(self.sn_selected)

    def get_devices(self):
        devices_sn = self.adb_devices()
        print len(devices_sn), "connected devices:", ", ".join(devices_sn)
        # 根据已有的设备进行增删
        devices_sn_old = self.devices.keys()
        devices_sn_remove = [sn for sn in devices_sn_old if sn not in devices_sn]
        if len(devices_sn_remove):
            print "remove", len(devices_sn_remove), "device(s)"
        for sn in devices_sn_remove:
            self.devices.pop(sn)
        devices_sn_add = [sn for sn in devices_sn if sn not in devices_sn_old]
        if len(devices_sn_add):
            print "add", len(devices_sn_add), "device(s)"
        for sn in devices_sn_add:
            device_info = self.adb_device_info(sn)
            # device_info.append(device_sn)
            self.devices[sn] = " ".join(device_info)  # 以android studio的设备显示格式来显示设备
        if len(self.devices) < 1:
            self.devices["no connect!"] = "no device!"  # 处理空值
        self.devices_sn = self.devices.keys()
        return self.devices.values()

    @staticmethod
    def adb_device_info(device_sn):
        # print "get device info"
        brand = os.popen("adb -s %s shell getprop ro.product.brand" % device_sn).read()
        model = os.popen("adb -s %s shell getprop ro.product.model" % device_sn).read()
        version = "Android " + os.popen("adb -s %s shell getprop ro.build.version.release" % device_sn).read()
        api_level = ",API " + os.popen("adb -s %s shell getprop ro.build.version.sdk" % device_sn).read()
        return [brand, model, version, api_level]

    def adb_devices(self):
        command = 'adb devices'
        devices_sn = []
        adb_out = self.adb.cmd(command, need_result=True).readlines()
        for line in adb_out:
            m = re.match(r"(\S+)\tdevice", line)
            if m:
                devices_sn.append(m.group(1))
        return devices_sn

# todo：合入adb相关的操作指令，adbutils先只放入os.popen的指令，后面再接口化同时对接socket方式和popen方式
class AdbUtils:
    def __init__(self):
        self.adb = AdbCore()
        self.adb_devices = AdbDevices(self.adb)

        self.sn_selected = ""
        self.devices_sn = []
        self.devices = {}


if __name__ == "__main__":
    def print_log(log_str):
        print log_str
    a = AdbUtils()
    a.adb.set_sn("0815f84901a31004")
    a.logcat.set_filter("| grep -E 'StatLogger.*logtype'")
    print "start..."
    a.logcat.start(print_log)